package com.example.order.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.bean.Order;
import com.example.order.properties.OrderProperties;
import com.example.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@CrossOrigin
@RestController
//@RequestMapping("/api/order")
//@RefreshScope// 激活配置属性的自动刷新功能
public class OrderController {

    @Autowired
    OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeOut;
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;

    @Autowired
    OrderProperties orderProperties;


    @GetMapping("/config")
    public String config() {
        return "orderTimeOut:" + orderProperties.getTimeOut() + ";" +
                " orderAutoConfirm:" + orderProperties.getAutoConfirm() + "; " +
                " dbUrl:" + orderProperties.getDbUrl();
    }

    /**
     * 创建订单
     *
     * @param userId
     * @param productId
     * @return
     */
    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        return order;
    }


    /**
     * 秒杀订单
     *
     * @param userId
     * @param productId
     * @return
     */
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", blockHandler = "seckillFallback")
//    @SentinelResource(value = "seckill-order", Fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "userId", required = false) Long userId,
                         @RequestParam(value = "productId", defaultValue = "1000") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    //                                                          全部异常，下面是block异常
    //public Order seckillFallback(Long userId, Long productId, Throwable exception)
    public Order seckillFallback(Long userId, Long productId, BlockException exception) {
        System.out.println("seckillFallback兜底回调");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息：" + exception.getClass());
        return order;
    }


    @GetMapping("/writeDb")
    public String writeDb() {
        return "writeDb success....";
    }

    @GetMapping("/readDb")
    public String readDb() {
        log.info("readDb");
        return "readDb success....";
    }
}
